package org.canaan.http;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URLEncoder;

/**
 * @author Canaan
 * @date 2017/7/17
 */
public class UrlPairUtil {
    public static boolean isBaseType(Object o){
        if (o == null) {
            return true;
        }
        if (Integer.class.isInstance(o)) {
            return true;
        }else if(BigInteger.class.isInstance(o)){
            return true;
        }else if(BigDecimal.class.isInstance(o)){
            return  true;
        } else if (String.class.isInstance(o)) {
            return true;
        } else if (Float.class.isInstance(o)) {
            return true;
        } else if (Double.class.isInstance(o)) {
            return true;
        } else if (Short.class.isInstance(o)) {
            return true;
        } else if (Long.class.isInstance(o)) {
            return true;
        } else if (Character.class.isInstance(o)) {
            return  true;
        } else if (Boolean.class.isInstance(o)) {
            return true;
        } else if (Byte.class.isInstance(o)) {
            return true;
        }
        return false;

    }

    public static Object urlEncoder(Object object) {
        if (object == null) return "";
        if (String.class.isInstance(object)) {
            try {
                return URLEncoder.encode(object.toString(), "utf-8");
            } catch (UnsupportedEncodingException e) {
                return "";
            }
        }
        return object;
    }

    public static String chinaToUnicode(String str){
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            int chr1 = str.charAt(i);
            if ((chr1 >= 128) && (chr1 <= 171941)) {
                String unicode = String.valueOf(Integer.toHexString(chr1));
                result.append("\\u").append(formatUnicode(unicode));
            } else {
                result.append(str.charAt(i));
            }
        }
        return result.toString();
    }

    public static String formatUnicode(String unicode){
        int length = 4 - unicode.length();
        for (int i = 0; i < length; i++) {
            unicode = "0" + unicode;
        }
        return unicode;
    }
}
